package com.anteater.eattheant.util;

import java.util.Iterator;

public class Stack<T> implements Iterable<T> {

	int head;
	private T[] array;

	@SuppressWarnings("unchecked")
	public Stack(int capacity) {
		head = -1;
		array = (T[]) new Object[capacity];
	}

	public boolean isEmpty() {
		return head < 0;
	}

	public T element() {
		return isEmpty() ? null : array[head];
	}

	public T elementAt(int i) {
		if (i < -head-1 || i > head) {
			return null;
		}
		
		if (i < 0) {
			return array[head+i+1];
		} else {
			return array[i];
		}
	}
	
	public boolean push(T element) {
		if (head == array.length) {
			return false;
		}
		array[++head] = element;
		return true;
	}

	public T pop() {
		if (isEmpty()) {
			return null;
		}
		return array[head--];
	}
	
	public int size() {
		return head+1;
	}

	@Override
	public Iterator<T> iterator() {
		return new Iterator<T>() {
			int pointer = 0;

			@Override
			public boolean hasNext() {
				return pointer <= head;
			}

			@Override
			public T next() {
				return array[pointer++];
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}
}
